<template>
  <div id="app">
    <router-view id="children" :chartIds='chartIds' :chartFlag="chartFlag" :chartOutlineIds="chartOutlineIds" :chartOnlineIds="chartOnlineIds" />
    <!-- 赠送礼物弹框提示 {{gift.num}}{{gift.name}}-->
     <div class="gift_popup" v-show="giftFlag">
          <span class="gift_popup_name">{{gift.username}}</span>&nbsp;&nbsp;
          {{$t('m.msg.MSG106')}}<span class="gift_popup_gift">&nbsp;&nbsp;{{gift.name}}x{{gift.num}}</span>
      </div>
      <!-- 赠送表情弹框提示 {{gift.num}}{{gift.name}}-->
     <div class="gift_popup" v-show="expressionFlag">
          <span class="gift_popup_name">{{expression.username}}</span>&nbsp;&nbsp;
          {{$t('m.msg.MSG106')}}<span class="gift_popup_gift">&nbsp;&nbsp;{{$t('m.msg.MSG107')}}</span>
      </div>
  </div>
</template>

<style >
  @import './font-awesome/css/font-awesome.min.css';
  .nonedata{/*无数据图片样式*/
    height: 91.6vh;
    width: 100vw;
  }
  .gift_popup{
    position: fixed;
    top: 0;
    height: 10vh;
    width: 100vw;
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28px;
    background-color: white;
    border-bottom: 2px #a1a1a1 solid;
    border-radius: 30px;
    animation:mymove 5s infinite;
    -moz-animation:mymove 5s infinite; /* Firefox */
    -webkit-animation:mymove 5s infinite; /* Safari and Chrome */
    -o-animation:mymove 5s infinite; /* Opera */
    animation-iteration-count:1;
  }

  @keyframes mymove {
      0% {top:-10vh;}
      25% {top:0px;}
      75% {top:0px;}
      100% {top:-10vh;}
    }

    @-moz-keyframes mymove {
      0% {top:-10vh;}
      25% {top:0px;}
      75% {top:0px;}
      100% {top:-10vh;}
    }
    @-o-keyframes mymove {
      0% {top:-10vh;}
      25% {top:0px;}
      75% {top:0px;}
      100% {top:-10vh;}
    }
    @-webkit-keyframes mymove {
      0% {top:-10vh;}
      25% {top:0px;}
      75% {top:0px;}
      100% {top:-10vh;}
    }

  .gift_popup_gift{
    color: red;
    font-size: 30px;
  }

  .gift_popup_name{
    font-size: 30px;
    color: blue;
  }

</style>

<script lang="ts">
import Vue from 'vue'
import {getUser,removeUser} from './api/session.js'
import  base from './config/base.js'
import websoketConstant from './api/socketConstant'
import { postQuery,getLanguage} from './api/query'
export default Vue.extend({
  name: 'app',
  components: {

  },
  data(){
    return{
      ws: {},
      gift: {},
      giftFlag: false,
      // status: false,//记录是否执行连接操作
      errorNum: 1,//记录错误数
      // openNum: 18,//重连次数
      chartFlag: false, //是否有消息
      chartOnlineIds: [], //上线通知
      chartOutlineIds: [],//下线通知
      sendFlag: true,
      interval: {},
      expressionFlag:false,
      expression: {},
      // sendInterval: null,
      chartIds: []//消息来源id    
    }
  },
  methods: {
    getMessage(msg) {
      let that = this;
        console.log('app:接收消息   ',msg)
        if(msg){
         
            let res = JSON.parse(msg.data);
             //提示信息
            if(websoketConstant.msgError == res.msgType){
                that.$toast.fail(res.content);
            }else if(websoketConstant.logonFailure == res.msgType){
                that.$toast.fail(res.content);
                that.$router.push({
                    path:'/login'
                })
            } 
            if(websoketConstant.userLogoff == res.msgType){
              that.chartOutlineIds = [];
              // that.chartOnlineIds = [];
              let content = JSON.parse(res.content);
              console.log('下线：',content)
              that.chartOutlineIds.push(content.id)
            }
            if(websoketConstant.usersOnline == res.msgType){
              // that.chartOutlineIds = [];
              that.chartOnlineIds = [];
               let content = JSON.parse(res.content);
                console.log('上线：',content)
              that.chartOnlineIds.push(content.id)
            }
            if(websoketConstant.receiveMsg == res.msgType){
              let content = JSON.parse(res.content);
              // 接收到的消息
              console.log('接收到的消息：',content)
              
              let flag = true;
              for(let i = 0; i < that.chartIds.length; i ++){
                if(that.chartIds[i] == content.fromMemberId){
                  flag = false;
                  break;
                }
              }
               console.log('接收到的消息ids：',that.chartIds, flag)
              if(flag){
                that.chartIds.push(content.fromMemberId);
                that.chartFlag = true;
              }
            }
            if(websoketConstant.gift == res.msgType){
              let content = JSON.parse(res.content);
              that.gift = content.gift;
              that.gift.username = content.from.name
              //弹框提醒
              that.giftFlag = true;
              //五秒之后为false
              setTimeout(() => {
                that.giftFlag = false;
              }, 5000);
            }
            if(websoketConstant.toExpression == res.msgType){
              let content = JSON.parse(res.content);
              that.expression = content.expression;
              that.expression.username = content.from.name
              //弹框提醒
              that.expressionFlag = true;
              //五秒之后为false
              setTimeout(() => {
                that.expressionFlag = false;
              }, 5000);
            }
            // console.log(JSON.parse(res))
            
        }
    },
    init() {
      let that = this;
      if(typeof(WebSocket) === "undefined"){
          that.$toast.fail("您的浏览器不支持socket")
      }else{
          // 实例化socket
          // console.log(that.ws)
          // if(!that.ws){
          let user = getUser();
          // console.log(user)
           that.ws = new WebSocket(base.getSocketUrl())
          // that.ws = new WebSocket(base.getSocketUrl() + '/' + user.cookie.sessionId + '/' + user.cookie.language)
          // }
          // console.log('app:',that.ws)
          // 监听socket连接
          that.ws.onopen = that.open
          // 监听socket错误信息
          that.ws.onerror = that.error
          //监听socket消息.close()
          that.ws.onmessage = that.getMessage
          that.ws.onclose = that.close
          if(that.sendFlag){
            that.interval = setInterval(function () {
              that.send();
            }, 5000);
            that.sendFlag = false
            // console.log(that.sendInterval)
          }
          
      }
    },
    //发送心跳
    send() {
        let that = this;
        let param = {
            uid: String(Date.parse(new Date())),
            msgType: "heartbeat",
            content: ''
        }
        if(that.ws.readyState !== 1){
          // console.log(that.sendInterval)
          //跳登录
          if(that.errorNum > 2){
            that.$toast.fail('连接不成功，请重新登录...')
            that.$router.push({
              path:'/login'  
            })
          }
          // if(that.errorNum > that.openNum){
          //   console.log(11111)
            that.$toast.fail('断线重连中...')
          //   clearInterval(that.sendInterval);
          // }else{
            that.status = false;
            that.init();
            that.errorNum ++;
          // }
         
        }else{
          that.ws.send(JSON.stringify(param))
        }

        
    },
    open() {
        console.log("socket连接成功")
    },
    error() {
      let that = this;
       console.log("连接错误")
      // if(that.errorNum > that.openNum){
      //   that.$toast.fail('连接失败，请稍后重试')
      //   return
      // }
      that.status = false;
      that.init();
      that.errorNum ++;
    },
    close() {
      let that = this;
      console.log("socket已经关闭")
      //  if(that.errorNum > that.openNum){
      //   return
      //   // that.$toast.fail('连接失败，请稍后重试')
      // }
      // that.status = false;
      // that.init();
      // that.errorNum ++;
    }
  },
  beforeUpdate(){
    let that = this;
    // console.log(that.$route.path !== '/login' && !that.status && 
    // that.$route.path !== '/' && that.$route.path !== '/register')
    //登录成功连接websocket
    console.log('luyou:',that.$route.path)
    if(that.$route.path !== '/login' && !that.status && that.$route.path !== '/forgetPass' && 
    that.$route.path !== '/index' && that.$route.path !== '/register'){
      that.status = true;
      // alert(111)
      that.init();
    }else if(that.$route.path === '/login' || that.$route.path === '/forgetPass' ||
    that.$route.path === '/index' || that.$route.path === '/register'){
    //   console.log('下线：',that.ws,that.$route.path !== '/login' && that.$route.path !== '/forgetPass' && 
    // that.$route.path !== '/index' && that.$route.path !== '/register')
    removeUser(); //将缓存清空
    console.log('下线：',that.ws)
      if(that.ws){
        if(that.ws.readyState === 1){
           that.ws.close();
           console.log('下线：',that.ws.readyState)
        }
      }
      that.status = false;
      if(that.interval){ //清除定时器
        clearInterval(that.interval);
      }
    }
    if(that.$route.path === '/chartList'){
      that.chartFlag = false;
    }

//     if(that.$route.path === '/chatIndex'){
// //  window.location.reload()
//     }
  },
  created(){

  
    //修改语言
    this.$i18n.locale = getLanguage();

    // console.log(this.$i18n.t('m.headernav.REIGSTER'))
  }
})
</script>
